package cn.codergege.demo.okhttp

import okhttp3.*
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.*
import org.springframework.boot.test.context.SpringBootTest
import java.io.IOException


//@SpringBootTest
class GetDemoTest {
    lateinit var client: OkHttpClient
    lateinit var baidu: String

//    @BeforeEach
    fun setup() {
        client = OkHttpClient()
        baidu = "https://www.baidu.com"
    }

//    @Test
    fun testSyncGet() {
        // 不只是可以设置 url() 还有很多
        val request = Request.Builder().url(baidu).build()
        // use 的使用?
        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) throw IOException("Unexpected code $response")

            val responseHeaders = response.headers()
            for (i in 0 until responseHeaders.size()) {
                println(responseHeaders.name(i) + ": " + responseHeaders.value(i))
            }
            println("***********************************")
//            println(response.body()?.string())
        }
    }

//    @Test
    fun testAsyncGet() {
        val request = Request.Builder()
            .url("http://publicobject.com/helloworld.txt")
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                response.body().use { responseBody ->
                    if (!response.isSuccessful()) throw IOException("Unexpected code $response")

                    val responseHeaders = response.headers()
                    for(i in 0 until responseHeaders.size())
                        println("${responseHeaders.name(i)}: ${responseHeaders.value(i)}")
                    println("**********")
//                    println(responseBody?.string())
                }
            }
        })
    }


}